package com.ruoyi.tester.login;

import com.ruoyi.tester.domain.TesterLoginConfig;
import com.ruoyi.tester.domain.TesterLoginRst;
import com.ruoyi.tester.mapper.TesterLoginConfigMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author SongJun
 * @description TODO:
 * @date 2022/4/18 10:39
 */
public class LoginCache {
    private static Logger logger = LoggerFactory.getLogger(LoginCache.class);

    private static Map<Long, TesterLoginRst> cache = new ConcurrentHashMap<>();
    private static TesterLoginConfigMapper testerLoginConfigMapper;

    public static void initTesterLoginConfigMapper(TesterLoginConfigMapper mapper){
        if(testerLoginConfigMapper == null){
            testerLoginConfigMapper = mapper;
        }
    }

    public static TesterLoginRst getCache(Long loginConfigId){
        TesterLoginRst testerLoginRst = cache.get(loginConfigId);
        if(testerLoginRst == null || System.currentTimeMillis() - testerLoginRst.getLoginMillSecond() > testerLoginRst.getConfig().getTerm() * 1000){
            synchronized (cache){
                testerLoginRst = cache.get(loginConfigId);
                if(testerLoginRst == null || System.currentTimeMillis() - testerLoginRst.getLoginMillSecond() > testerLoginRst.getConfig().getTerm() * 1000) {
                    TesterLoginConfig config = getLoginBaseInfo(loginConfigId);
                    Login handler = LoginHandlerContainer.getLoginHandler(config.getLoginType());
                    TesterLoginRst loginResponse = handler.doLogin(loginConfigId);
                    LoginCache.setCache(loginConfigId, loginResponse);
                }
            }
        }
        return cache.get(loginConfigId);
    }

    public static void setCache(Long loginConfigId, TesterLoginRst testerLoginRst){
        cache.put(loginConfigId, testerLoginRst);
    }

    public static TesterLoginConfig getLoginBaseInfo(Long loginConfigId){
        TesterLoginConfig baseInfo = null;
        TesterLoginRst testerLoginRst = cache.get(loginConfigId);
        if(testerLoginRst == null){
            synchronized (cache){
                testerLoginRst = cache.get(loginConfigId);
                if(testerLoginRst == null){
                    baseInfo = testerLoginConfigMapper.selectTesterLoginConfigByLoginConfigId(loginConfigId);
                    TesterLoginRst rst = new TesterLoginRst(null, 0L, baseInfo);
                    setCache(loginConfigId, rst);
                } else {
                    baseInfo = testerLoginRst.getConfig();
                }
                if(baseInfo == null){
                    logger.error("{}未查询到对应的登录配置信息", loginConfigId);
                }
            }
        } else {
            baseInfo = testerLoginRst.getConfig();
        }
        return baseInfo;
    }

}
